package com.project.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.project.security.dao.ActorDao;
import com.project.security.dao.MenuDao;
import com.project.security.dao.UsersDao;
import com.project.security.model.Actor;
import com.project.security.model.Menu;
import com.project.security.model.Users;

//2
public class MyUserDetailService implements UserDetailsService {

	private UsersDao usersDao;
	private MenuDao menuDao;
	private ActorDao actorDao;

	// 登录验证
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {

		User userdetail = null;
		// 这里应该可以不用再查了

		Users users = this.usersDao.queryByUser(username);
		Collection<GrantedAuthority> grantedAuths = obtionGrantedAuthorities(users);

		boolean enables = true;
		boolean accountNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean accountNonLocked = true;

		// 封装成spring security的user
		userdetail = new User(users.getUserName(), users.getPassword(),
				enables, accountNonExpired, credentialsNonExpired,
				accountNonLocked, grantedAuths);

		return userdetail;
	}

	/**
	 * Description：取得用户的权限 <br/>
	 * 
	 * @param user
	 * @return
	 */
	private Set<GrantedAuthority> obtionGrantedAuthorities(Users user) {
		Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();
		List<Menu> menus = new ArrayList<Menu>();

		Actor actor = actorDao.queryByActor(user.getActor());

		String role = actor.getRole();
		List menuList = new ArrayList();
		if (role != null && role.trim().length() > 0 && role.trim().indexOf(",") > -1) {

			String[] roles = role.split(",");
			for (int i = 0; i < roles.length; i++)
				menuList.add(Integer.parseInt(roles[i]));

		} else {
			menuList.add(Integer.parseInt(role));
		}
		
		Map strMap = new HashMap();
		strMap.put("menuList", menuList);
		
		menus = menuDao.queryByActor(strMap);
		for (Menu menu : menus) {
			authSet.add(new GrantedAuthorityImpl(menu.getMenuName()));
		}
		
		return authSet;
	}

	public void setActorDao(ActorDao actorDao) {
		this.actorDao = actorDao;
	}

	public void setMenuDao(MenuDao menuDao) {
		this.menuDao = menuDao;
	}

	public void setUsersDao(UsersDao usersDao) {
		this.usersDao = usersDao;
	}

}
